/*
 * practice code while learning <lucene in action>
 * searcher
 * mengchang@taobao.com
 * 2011-5-26
 */
package lucenetest;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

public class TestSearcher {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("in TestSearcher");
		//这个是lucene的javadoc文档所在的目录，其中的html文件，用英语写成
		String sourcedir="F:\\learning\\lucene-3.1.0\\lucene-3.1.0\\docs";
		String indexdir="F:\\learning\\lucenIndex";
		if (System.getProperty("os.name").equalsIgnoreCase("Linux")) 
		{
			sourcedir="/home/jiening/learning/lucene-3.1.0/lucene-3.1.0/docs";
			indexdir="/home/jiening/learning/luceneTestIndex";
		}
		System.out.println("sourcedir="+sourcedir);
		System.out.println("indexdir="+indexdir);
		
		try {
			Directory idxdir = new SimpleFSDirectory(new File(indexdir));
			IndexSearcher is = new IndexSearcher(idxdir, true);
			
			QueryParser queryobj = new QueryParser(
					Version.LUCENE_31, 
					"content", 
					new StandardAnalyzer(Version.LUCENE_31));
			Query query=null;
			try {
				query = queryobj.parse("QueryParser AND NOT IndexSearcher");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
					
			long start = new Date().getTime();
			TopDocs docs = is.search(query, 10);
			long end = new Date().getTime();
					
			System.err.println("Found " + docs.totalHits +" document(s) "+
					"(in " + (end - start) +" milliseconds) that matched query");
					
			for (int i = 0; i < docs.scoreDocs.length; i++) 
			{
					int docid = docs.scoreDocs[i].doc;
					float scorevalue = docs.scoreDocs[i].score;
					System.out.println("docid="+docid+",score="+scorevalue);
					
					Document tmpdoc = is.doc(docid);
					System.out.println("document:"+tmpdoc.getField("docid")+","+tmpdoc.getField("path"));
			}
			
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
